import os
from tkinter import *
import subprocess as sp
import tkinter.filedialog
import tkinter as tk
from tkinter import ttk
import subprocess
from serial.tools.list_ports import comports
from pathlib import Path
import ampy

#无弹窗设置
#pyinstaller -F -w --noconsole PyGUI.py
#subprocess.run(listcmdsd,capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW)

# 创建窗口
window = Tk()
# 设置窗口标题
window.title("My GUI")
# 设置窗口大小
window.geometry("500x500")
#创建多窗口
note = ttk.Notebook(window)
note.pack(fill="both", expand=True)
#########################################窗口2############################

#执行文件列表扫描
def runlistdir(dir):
        listcmdsd = ['ampy','--port','COM1','ls']
        listcmdsd[2] = var.get()
        listcmdsd.append(dir)
        filelist=subprocess.run(listcmdsd,capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW)
        if filelist.stderr != '':
            text2.insert(INSERT,"scan fail!"+'\n\r')
            text2.insert(1.0,filelist.stderr)
        else :
            text2.insert(INSERT,"scan ok!"+'\n\r')
            text2.insert(1.0,filelist.stdout)
            port_list2['value']=filelist.stdout
            port_list2.current(0)

#判断是选择的哪个DEV
def listdir():
    text2.delete(1.0, tk.END)
    if var1.get():
        runlistdir('/sd')
    if var2.get() :
        runlistdir('/flash')

#上传文件
def runupload(dev,filenamex):
    uplaodcmdtemp=['ampy','--port','COM1','put']
    uplaodcmdtemp[2] = var.get()
    uplaodcmdtemp.append(filenamex)
    uplaodcmdtemp.append('/'+dev+'/'+os.path.basename(filenamex))
    text3.insert
    print("命令是:",uplaodcmdtemp)
    uploadret=subprocess.run(uplaodcmdtemp,capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW,)
    if uploadret.stderr != '':
        text2.insert(INSERT,dev + " uploading fail!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)
    else :
        text2.insert(INSERT,dev + " uploading ok!"+'\n\r')
    #替换要执行的文件
    text3.delete(1.0, tk.END)
    text3.insert(INSERT,'/'+dev+'/'+os.path.basename(filenamex))
    text4.delete(1.0, tk.END)
    text4.insert(INSERT,os.path.basename(filenamex))
    del uplaodcmdtemp

#判断是选择的哪个DEV
def upload():
    text2.delete(1.0, tk.END)
    filename=tkinter.filedialog.askopenfilename()
    if filename != '':
        text2.insert(INSERT,'您选择的文件是:'+os.path.basename(filename)+'\n\r')
        if var1.get():
            runupload("sd",filename)
        if var2.get():
            runupload("flash",filename)
    else:
         text2.insert(INSERT,'\n\r 您没有选择任何文件!')

#删除指定文件
def rmfile():
    text2.delete(1.0, tk.END)
    file_name=text3.get('1.0', 'end-1c')
    delcmdtemp=['ampy','--port','COM1','rm']
    delcmdtemp[2] = var.get()
    delcmdtemp.append(file_name)
    text2.insert(INSERT,'你要删除的是:' + file_name +'\n\r')
    uploadret=subprocess.run(delcmdtemp,capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW)
    if uploadret.stderr != '':
        text2.insert(INSERT,"del fail!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)
    else :
        text2.insert(INSERT," del ok!"+'\n\r')

#执行指定文件
def runfile():
    text2.delete(1.0, tk.END)
    file_name=text4.get('1.0', 'end-1c')
    runcmdtemp=['ampy','--port','COM1','run','mixly.py']
    runcmdtemp[2] = var.get()
    runcmdtemp.append(file_name)
    text2.insert(INSERT,'你要执行的是:' + file_name +'\n\r')
    uploadret=subprocess.run('ampy --port COM19 reset --hard',capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW)
    if uploadret.stderr != '':
        text2.insert(INSERT,"reset fail!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)
    else :
        text2.insert(INSERT," reset ok!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)

#获取当前在线的串口端口
def search_ports():
    ports = comports()
    port_list.delete(0, tk.END)
    list_tup=[]
    for port, desc, hwid in sorted(ports):
        list_tup.append(f"{port}")
    port_list['value']=tuple(list_tup)
    port_list.current(0)


#下载文件
def rundownfile(filenamex,path_dir):
    uplaodcmdtemp=['ampy','--port','COM1','get']
    uplaodcmdtemp[2] = var.get()
    uplaodcmdtemp.append(filenamex)
    uplaodcmdtemp.append(os.path.normpath(path_dir) +'\\'+ os.path.basename(filenamex))
    uploadret=subprocess.run(uplaodcmdtemp,capture_output=True,text=True,creationflags=subprocess.CREATE_NO_WINDOW)
    if uploadret.stderr != '':
        text2.insert(INSERT,"down fail!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)
    else :
        text2.insert(INSERT," down ok!"+'\n\r')
        text2.insert(INSERT,uploadret.stderr)
    del uplaodcmdtemp
def downfile():
    text2.delete(1.0, tk.END)
    folder=tkinter.filedialog.askdirectory()
    filename = var3.get()
    path_dir=os.path.normpath(folder)
    text2.insert(INSERT,'您选择的文件是:'+filename+'\n\r')
    text2.insert(INSERT,'下载路径是:'+path_dir+'\n\r')
    rundownfile(filename,path_dir)

#创建右键菜单
def cut(editor, event=None):
    editor.event_generate("<<Cut>>")
def copy(editor, event=None):
    editor.event_generate("<<Copy>>")
def paste(editor, event=None):
    editor.event_generate('<<Paste>>')
def rightKey(event, editor):
    menubar.delete(0,END)
    menubar.add_command(label='剪切',command=lambda:cut(editor))
    menubar.add_command(label='复制',command=lambda:copy(editor))
    menubar.add_command(label='粘贴',command=lambda:paste(editor))
    menubar.post(event.x_root,event.y_root)

#创建窗口2
frm2 = ttk.Frame(note)
frm2.pack(fill="both", expand=True)
note.add(frm2, text="MicroPy")


#创建SD/FLASH复选框
var1 = tk.IntVar()
cb1 = Checkbutton(frm2,text="SD",variable=var1)
cb1.select()
cb1.place(x=6, y=5, width=55, height=15)
var2 = tk.IntVar()
cb2 = Checkbutton(frm2,text="FLASH",variable=var2)
cb2.place(x=15, y=25, width=55, height=15)

#创建刷新按钮，绑定回调函数
btn2 = Button(frm2,bd=3,text='刷新文件列表',command=listdir)
btn2.place(x=75, y=5, width=90, height=35)

#创建上传按钮，绑定回调函数
btn3 = Button(frm2,bd=3,text='上传文件',command=upload)
btn3.place(x=180, y=5, width=90, height=35)

#创建删除按钮，绑定回调函数
btn4 = Button(frm2,bd=3,text='删除',command=rmfile)
btn4.place(x=440, y=5, width=50, height=18)

#创建执行按钮，绑定回调函数
btn5 = Button(frm2,bd=3,text='复位',command=runfile)
btn5.place(x=440, y=25, width=50, height=18)


#创建右键菜单
menubar = Menu(frm2,tearoff=False)
#创建信息显示区
text2=Text(frm2,wrap=WORD)
text2.place(x=10, y=85, width=260, height=400)
text2.bind("<Button-3>", lambda x: rightKey(x, text2))#绑定右键鼠标事件

#创建删除文件填选框
text3=Text(frm2,wrap=WORD)
text3.place(x=280, y=5, width=150, height=18)
text3.bind("<Button-3>", lambda x: rightKey(x, text3))#绑定右键鼠标事件
#创建执行文件填选框
text4=Text(frm2,wrap=WORD)
text4.place(x=280, y=25, width=150, height=18)
text4.bind("<Button-3>", lambda x: rightKey(x, text4))#绑定右键鼠标事件

#创建端口刷新按钮
btn6=Button(frm2,bd=3,text='端口刷新',command=search_ports)
btn6.place(x=15, y=53, width=55, height=20)
#创建端口选择框
var = tkinter.StringVar()
port_list = ttk.Combobox(frm2,value=('COM19'),textvariable=var)
port_list.current(0)
port_list.place(x=75, y=53, width=90, height=20)

#创建下载按钮
btn7=Button(frm2,bd=3,text='下载文件',command=downfile)
btn7.place(x=180, y=45, width=90, height=35)
var3 = tkinter.StringVar()
port_list2 = ttk.Combobox(frm2,value=('File?'),textvariable=var3)
port_list2.current(0)
port_list2.place(x=280, y=50, width=210, height=25)

#########################################窗口2############################
#创建布局窗口
#frame = Frame(window)
#frame.pack(fill="both", expand=True)
frame = ttk.Frame(note)
frame.pack(fill="both", expand=True)
note.add(frame, text="日志筛查")
#创建滑动条
scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
#获取相对路径的按键图片
#file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bt.png')
#photo = tkinter.PhotoImage(file=file_path)
#创建按钮
#btn=Button(frame,bd=3,text='选择文件夹',image=photo)
#btn.pack()
# 创建标签
#lb = Label(frame,bd=10,anchor=W,text='')
#lb.pack()
#创建文本框
text=Text(frame,wrap=WORD)
print(Button.grid)
#绑定滚动条和文本框
text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)
text.pack(fill="both",expand=True)

# 运行窗口循环
window.mainloop()
